package com.example.acharten;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import org.achartengine.ChartFactory;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;

public class PieChart {
	private Map<Object, Object> datas;
	private String activityTitle;
	public DefaultRenderer buildCategoryRenderer(int[] colors) {
		DefaultRenderer renderer = new DefaultRenderer();
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		renderer.setMargins(new int[] { 20, 30, 15, 0 });
		for (int color : colors) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(color);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

	public DefaultRenderer getRenderer() {
		Random random = new Random();  
		int[] colors = new int[datas.size()];
		
		for (int i = 0; i < colors.length; i++) {
			colors[i] = Color.rgb(random.nextInt()*128+128 ,
					random.nextInt()*128+128, random.nextInt()*128+128);
		}
		DefaultRenderer renderer = buildCategoryRenderer(colors);
		renderer.setZoomButtonsVisible(true);
		renderer.setZoomEnabled(true);
		renderer.setApplyBackgroundColor(true);
		renderer.setBackgroundColor(Color.BLACK);
		renderer.setLabelsColor(Color.WHITE);
		renderer.setLabelsTextSize(20);
		return renderer;
	}

	public CategorySeries buildCategoryDataset(String title, Map<Object, Object> values) {
		CategorySeries series = new CategorySeries(title);
//		int k = 0;
		Iterator<Entry<Object, Object>> it = values.entrySet().iterator();
		
		while (it.hasNext()) {
			Entry<Object, Object> eoo = it.next();
			series.add(eoo.getKey().toString(), Double.parseDouble(eoo.getValue().toString()));
		}
//		for (double value : values) {
//			series.add("Project " + ++k, value);
//		}

		return series;
	}
	
	public CategorySeries getDataSet() {
		return this.buildCategoryDataset(activityTitle, datas);
	}
	
	public Intent createPieChatIntent(Context context, Map<Object, Object> datas, String activityTitle) {
		this.datas = datas;
		this.activityTitle = activityTitle;
		 Intent intent = ChartFactory.getPieChartIntent(context, getDataSet(), getRenderer(), activityTitle);
		return intent;
		
	}
}
